#!/usr/bin/env python2

import os
import sys
import socket
import time
import subprocess
import fcntl
import types
import errno
import getopt
import random
import threading
import traceback
import json
import urllib
import logging
import logging.handlers

from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from SocketServer import ThreadingMixIn
from Ump.common import config,oem_conf
#import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler

#sys.path.insert(0, os.path.split(os.path.realpath(__file__))[0] + "/../")

from daemon import Daemon
from utils import Exp, _dmsg, _dwarn, _derror, _str2dict, _getrack, _http_down
from Ump.utils import install_path


LOG = logging.getLogger('Ump.proxy.lich_dump')


class Handler(BaseHTTPRequestHandler):
    def __sendfile(self, fd, size):
        left = size
        self.wfile.write(fd)
        return

    def __get_io(self, path):
        #tmp = config + '/tmp/dump'
        tmp = '%s/tmp/ump/dump' % install_path
        host = path.strip().split('?')[-1]
        content, content_length = _http_down(host, '27902', '/io.tar.gz')
        self.send_response(200)
        self.send_header('Content-type', 'application/gzip')
        self.send_header('Content-length', str(int(content_length)))
        self.end_headers()

        self.__sendfile(content,content_length)
        return

    def do_GET(self):
        path = urllib.unquote(self.path)
        if (path.startswith('/io.tar.gz') and not path.find('?') == -1):
            self.__get_io(path)
        else:
            self.send_response(404)
            self.end_headers()

class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
    """Handle requests in a separate thread."""

class Lich_Dump(Daemon):
    def __init__(self):
        self.config = install_path
        os.system('mkdir -p ' + self.config + '/tmp')
        os.system('mkdir -p ' + self.config + '/log')
        pidfile = '/var/run/ump_proxy_download.pid'
        log = self.config + '/log/ump_proxy_download.log'
        os.system('touch ' + log)
        super(Lich_Dump, self).__init__(pidfile, '/dev/null', log, log, 'ump-proxy-downlod')

    def run(self):
        #sys.stdout.write('out:run\n')
        #sys.stderr.write('err:run\n')
        server = ThreadedHTTPServer(('', int(config.proxy_download_port)), Handler)
        LOG.info("start server : 127.0.0.1:%s" % config.proxy_download_port)
        server.serve_forever()

def usage():
    print ("usage:")
    print (sys.argv[0] + " --start")
    print (sys.argv[0] + " --stop")
    print (sys.argv[0] + " --test")
    print (sys.argv[0])

def main():
    op = ''
    ext = None
    try:
        opts, args = getopt.getopt(
                sys.argv[1:], 
            'h', ['start', 'stop', 'help', 'test']
                )
        if not opts:
            usage()
    except getopt.GetoptError, err:
        LOG.info(str(err))
        usage()

    lich_dump = Lich_Dump()
    for o, a in opts:
        if o in ('--help'):
            usage()
            exit(0)
        elif (o == '--start'):
            op = o
            lich_dump.start()
        elif (o == '--stop'):
            op = o
            lich_dump.stop()
        elif (o == '--test'):
            lich_dump.run()
        else:
            assert False, 'oops, unhandled option: %s, -h for help' % o
            exit(1)

if __name__ == '__main__':
    if (len(sys.argv) == 1):
        usage()
    else:
        main()
